package com.ctw.mall.controller;

import com.ctw.mall.consts.MallConst;
import com.ctw.mall.form.CartAddForm;
import com.ctw.mall.form.CartUpdateForm;
import com.ctw.mall.pojo.User;
import com.ctw.mall.service.ICartService;
import com.ctw.mall.vo.CartVo;
import com.ctw.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * 表单统一验证
 */
@RestController
public class CartController {

    @Autowired
    private ICartService cartService;

    //购物车列表
    @GetMapping("/carts")
    public ResponseVo<CartVo>  list(HttpSession session){
        //从session当中获取uid
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return  cartService.list(user.getId());
    }

    //往购物车内添加商品
    @PostMapping("/carts")
    public ResponseVo<CartVo>  add(@Valid @RequestBody CartAddForm cartAddForm,
                                   HttpSession session){
       //从session当中获取uid
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return  cartService.add(user.getId(),cartAddForm);
    }

    @PutMapping("/carts/{productId}")
    public ResponseVo<CartVo>  update(@PathVariable Integer productId
                                    ,@Valid @RequestBody CartUpdateForm form,
                                   HttpSession session){
        //从session当中获取当前对象的uid
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return  cartService.update(user.getId(),productId,form);
    }

    @DeleteMapping("/carts/{productId}")
    public ResponseVo<CartVo>  delete(@PathVariable Integer productId,
                                   HttpSession session){
        //从session当中获取uid
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return  cartService.delete(user.getId(),productId);
    }

    @PutMapping("/carts/selectAll")
    public ResponseVo<CartVo>  selectAll(HttpSession session){
        //从session当中获取uid
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return  cartService.selectAll(user.getId());
    }

    @PutMapping("/carts/unSelectAll")
    public ResponseVo<CartVo>  unSelectAll(HttpSession session){
        //从session当中获取uid
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return  cartService.unSelectAll(user.getId());
    }

    @GetMapping("/carts/products/sum")
    public ResponseVo<Integer>  sum(HttpSession session){
        //从session当中获取uid
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return  cartService.sum(user.getId());
    }
}
